package com.outsourcing.bottle.ui;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ZoomControls;

import com.aviary.android.feather.Constants;
import com.aviary.android.feather.FeatherActivity;
import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.BottleApplication;
import com.outsourcing.bottle.util.ServiceUtils;
import com.outsourcing.bottle.util.UICore;
import com.outsourcing.bottle.util.Utility;
import com.outsourcing.bottle.widget.ImageZoomView;
import com.outsourcing.bottle.widget.SimpleZoomListener;
import com.outsourcing.bottle.widget.ZoomState;
/**
 * 查看图片 双手触摸放大缩小，单手拖放
 * @author 06peng
 *
 */
public class PhotoDetailActivity extends BasicActivity implements OnClickListener, Callback {

	private String mPicPath = null;
	private ImageView bt_back = null;
	private ImageView bt_save = null;
	private Bitmap bmp;  
	private byte[] tempBytes;
	private Bitmap tempBmp;
	

	/**是否点击涂鸦进来此页面的*/
	private boolean isToDraw;
	/**从哪个界面进来的涂鸦照片*/
	private String mPaintType;
	/**瓶子ID*/
	private int btid;
	private String return_type;
	/**照片ID*/
	private int picId;
	/**交换会话中  对方的id*/
	private int ouid;
	
	private ImageZoomView mZoomView;
	private ZoomState mZoomState;
	private SimpleZoomListener mZoomListener;
	
	private final static int download_pic = 1;
	private final static int to_draw_pic = 2;
	private static final int RESULT_DRAW_IMAGE = 3;
	private Handler handler;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.showimageview);
		handler = new Handler(this);
		
		Intent intent = getIntent();
		mPicPath = intent.getStringExtra("pic_big");
		tempBytes = intent.getByteArrayExtra("thumbnail");
		isToDraw = intent.getBooleanExtra("isToDraw", false);
		
		mPaintType = intent.getStringExtra("paintType");
		btid = intent.getIntExtra("btid", 0);
		return_type = intent.getStringExtra("return_type");
		
		picId = intent.getIntExtra("picid", 0);
		ouid = intent.getIntExtra("ouid", 0);
		
		bt_back = (ImageView) findViewById(R.id.topbar_back);
		bt_save = (ImageView) findViewById(R.id.topbar_confirm);
		bt_back.setOnClickListener(this);
		bt_save.setOnClickListener(this);
		
		mZoomView = (ImageZoomView) findViewById(R.id.zoomView);
		
		if (tempBytes != null) {
			tempBmp = ServiceUtils.bytesToBitmap(tempBytes);
		} else {
			tempBmp = ServiceUtils.drawableToBitmap(getResources().getDrawable(R.drawable.album_nophoto));
		}
		if (tempBmp != null) {
			mZoomView.setImageBitmap(tempBmp);
			mZoomView.invalidateImage();
		}
		if (mPicPath != null) {
			DownloadImgTask task = new DownloadImgTask();
			task.execute(mPicPath);
			mZoomView.setPorterDuffMode(true);
			mZoomView.setLoading(true);
			mZoomView.setProgress(0);
			mZoomView.invalidate();
		}
	}

	@Override
	public void onClick(View v) {
		if (v == bt_back) {
			finish();
		} else if (v == bt_save) {
			UICore.eventTask(this, this, download_pic, "download_pic", null);
		} 
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case download_pic:
			downloadImage();
			break;
		default:
			break;
		}
	}
	
	private void downloadImage() {
		ServiceUtils.downLoadImage(mPicPath, AppContext.SD_PATH + "/download");
		if (isToDraw) {
			Message msg = Message.obtain(handler);
			msg.what = to_draw_pic ;
			msg.obj = AppContext.SD_PATH + "/download/"+mPicPath;
			handler.sendMessage(msg);
		}else {
			handler.sendEmptyMessage(download_pic);	
		}
		
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (bmp != null)
			bmp.recycle();
		 mZoomView.setOnTouchListener(null);
		 if (mZoomState != null) {
			 mZoomState.deleteObservers();
		 }
	}
	
	private void resetZoomState() {
		mZoomState.setPanX(0.5f);
		mZoomState.setPanY(0.5f);
		mZoomState.setZoom(1f);
		mZoomState.notifyObservers();
	}

	public class DownloadImgTask extends AsyncTask<String, Float, Bitmap> {
		private static final String TAG = "DownloadImgTask";

		/** 下载准备工作。在UI线程中调用。 */
		protected void onPreExecute() {
			Log.i(TAG, "onPreExecute");
		}

		/** 执行下载。在背景线程调用。 */
		protected Bitmap doInBackground(String... params) {
			
	     	Bitmap bmp = null;
        	bmp = ((BottleApplication)PhotoDetailActivity.this.getApplication()).getLruImageCache().get(params[0]);
        	if (null != bmp) {
        		if (isToDraw) {
        			try {
    					File file = Utility.getNextFileName();
    					FileOutputStream fs = new FileOutputStream(file);
    					ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    					bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);  
    					fs.write(baos.toByteArray());
    					baos.close();
    					fs.close();		
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				return bmp;
			} else {
				Log.i(TAG, "doInBackground:" + params[0]);
				HttpClient httpClient = new DefaultHttpClient();
				HttpGet httpGet = new HttpGet(params[0]);
				InputStream is = null;
				ByteArrayOutputStream baos = null;
				try {
					HttpResponse httpResponse = httpClient.execute(httpGet);
					printHttpResponse(httpResponse);
					HttpEntity httpEntity = httpResponse.getEntity();
					long length = httpEntity.getContentLength();
					Log.i(TAG, "content length=" + length);
					is = httpEntity.getContent();
					if (is != null) {
						baos = new ByteArrayOutputStream();
						byte[] buf = new byte[128];
						int read = -1;
						int count = 0;
						while ((read = is.read(buf)) != -1) {
							baos.write(buf, 0, read);
							count += read;
							publishProgress(count * 1.0f / length);
						}
						Log.i(TAG, "count=" + count + " length=" + length);
						byte[] data = baos.toByteArray();
						if (isToDraw) {
							File file = Utility.getNextFileName();
							FileOutputStream fs = new FileOutputStream(file);
							fs.write(data);
							fs.close();	
						}
						Bitmap bit = BitmapFactory.decodeByteArray(data, 0, data.length);
	    				((BottleApplication)PhotoDetailActivity.this.getApplication()).getLruImageCache().put(params[0], bit);
						return bit;
					}
				} catch (ClientProtocolException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					try {
						if (baos != null) {
							baos.close();
						}
						if (is != null) {
							is.close();
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			
			return null;
		}

		/** 更新下载进度。在UI线程调用。onProgressUpdate */
		protected void onProgressUpdate(Float... progress) {
			// LogOut.out(this, "onProgressUpdate");
			mZoomView.setProgress(progress[0]);
		}

		/** 通知下载任务完成。在UI线程调用。 */
		protected void onPostExecute(Bitmap bit) {
			Log.i(TAG, "onPostExecute");
			mZoomView.setPorterDuffMode(false);
			mZoomView.setLoading(false);
			mZoomView.setImageBitmap(bit);
			mZoomView.setImage(bit);
			mZoomState = new ZoomState();
			mZoomView.setZoomState(mZoomState);
			mZoomListener = new SimpleZoomListener();
			mZoomListener.setZoomState(mZoomState);
			mZoomView.setOnTouchListener(mZoomListener);
			ZoomControls zoomCtrl = (ZoomControls) findViewById(R.id.zoomCtrl);
			zoomCtrl.setOnZoomInClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					float z = mZoomState.getZoom() + 0.25f;
					mZoomState.setZoom(z);
					mZoomState.notifyObservers();
				}
			});
			zoomCtrl.setOnZoomOutClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					float z = mZoomState.getZoom() - 0.25f;
					mZoomState.setZoom(z);
					mZoomState.notifyObservers();
				}
			});
			resetZoomState();
			
			if (isToDraw) {
				Message msg = Message.obtain(handler);
				msg.what = to_draw_pic ;
//				msg.obj = AppContext.SD_PATH + "/download/"+mPicPath;
				handler.sendMessage(msg);
			}
		}

		protected void onCancelled() {
			Log.i(TAG, "DownloadImgTask cancel...");
			super.onCancelled();
		}

		private void printHttpResponse(HttpResponse httpResponse) {
			Header[] headerArr = httpResponse.getAllHeaders();
			for (int i = 0; i < headerArr.length; i++) {
				Header header = headerArr[i];
				Log.i(TAG, "name[" + header.getName() + "]value[" + header.getValue() + "]");
			}
			HttpParams params = httpResponse.getParams();
			Log.i(TAG, String.valueOf(params));
			Log.i(TAG, String.valueOf(httpResponse.getLocale()));
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case download_pic:
			onToast("Download Finish！");
			break;
		case to_draw_pic:
			File resultfile = Utility.getNextFileName();
			Uri fileUri = Uri.fromFile(resultfile);
			Intent newIntent = new Intent( this, FeatherActivity.class );
			newIntent.putExtra( "From_Type", Constants.ACTIVITY_DRAW );
			newIntent.setData( fileUri );
			newIntent.putExtra( "API_KEY", Utility.API_KEY );
			newIntent.putExtra( "output", Uri.parse( "file://" +  resultfile.getAbsolutePath() ) );
			newIntent.putExtra( Constants.EXTRA_OUTPUT_FORMAT, Bitmap.CompressFormat.PNG.name() );
			newIntent.putExtra( Constants.EXTRA_OUTPUT_QUALITY, 100 );
			newIntent.putExtra( Constants.EXTRA_TOOLS_DISABLE_VIBRATION, true );
			final DisplayMetrics metrics = new DisplayMetrics();
			((Activity)this).getWindowManager().getDefaultDisplay().getMetrics( metrics );
			int max_size = Math.min( metrics.widthPixels, metrics.heightPixels );
			max_size = (int) ( (double) max_size / 0.8 );
			newIntent.putExtra( "max-image-size", max_size );
			newIntent.putExtra( "effect-enable-borders", true );
//			mSessionId = StringUtils.getSha256( System.currentTimeMillis() + Utility.API_KEY );
//			newIntent.putExtra( "output-hires-session-id", mSessionId );
			startActivityForResult(newIntent, RESULT_DRAW_IMAGE);
			overridePendingTransition(R.anim.translate_right_in, R.anim.translate_left_in);
			break;
		default:
			break;
		}
		return false;
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			if (requestCode == RESULT_DRAW_IMAGE ) {
				File file = Utility.getNextFileName();
				updateMedia( file.getAbsolutePath() );
				
				if (null != mPaintType) {
					
					if (mPaintType.equals(AppContext.PAINT_BT)) {

						Intent commentIntent = new Intent(this,
								ExpandEditActivity.class);
						Bundle commentBundle = new Bundle();
						commentBundle.putString("from_type",
								AppContext.PAINT_BT);
						commentBundle.putInt("bttype_id", btid);
						commentBundle.putString("return_type", return_type);
						commentIntent.putExtras(commentBundle);
						startActivity(commentIntent);
						
					}else if (mPaintType.equals(AppContext.PAINT_PICEX)) {
						
						Intent commentIntent = new Intent(this,
								ExpandEditActivity.class);
						Bundle commentBundle = new Bundle();
						commentBundle.putString("from_type",
								AppContext.PAINT_PICEX);
						commentBundle.putInt("ouid", ouid);
						commentBundle.putInt("picid", picId);
						commentBundle.putString("return_type", return_type);
						commentIntent.putExtras(commentBundle);
						startActivity(commentIntent);
						
					}else if (mPaintType.equals(AppContext.PAINT_PHOTO)) {
						
						Intent commentIntent = new Intent(this,
								ExpandEditActivity.class);
						Bundle commentBundle = new Bundle();
						commentBundle.putString("from_type",
								AppContext.PAINT_PHOTO);
						commentBundle.putInt("picid", picId);
						commentIntent.putExtras(commentBundle);
						startActivity(commentIntent);
						
					}
				}
				
			}
		}
		finish();

	}
	private void updateMedia( String filepath ) {
		MediaScannerConnection.scanFile( getApplicationContext(), new String[] { filepath }, null, null );
	}
	
}
